package com.magicstone.common.Licence.service;

public class Convertor {
	// 将字符转化为字节

	public static byte[] charToByte(char ch) {
		int temp = (int) ch;
		byte[] b = new byte[2];
		// 将高8位放在b[0],将低8位放在b[1]
		for (int i = 1; i > -1; i--) {
			b[i] = (byte) (temp & 0xFF);// 低8位
			// 向右移8位
			temp >>= 8;
		}
		return b;
	}

	// 将字节转化为比特数组
	public static byte[] byteToBitArray(byte b) {
		// 强制转换成int?
		int temp = (int) b;
		byte[] result = new byte[8];
		for (int i = 7; i > -1; i--) {
			result[i] = (byte) (temp & 0x01);
			temp >>= 1;
		}
		return result;
	}

	// 将二维比特数组转化为字节
	public static byte bitToByteArray(byte[] b) {
		byte result;
		result = (byte) (b[7] | b[6] << 1 | b[5] << 2 | b[4] << 3 | b[3] << 4
				| b[2] << 5 | b[1] << 6 | b[0] << 7);
		return result;
	}

	public static void main(String[] args) {
		for (byte b : charToByte('a')) {
			System.out.println(b);
		}
	}

	// 将字节转化为字符
	public static char byteToChar(byte[] b) {
		int s = 0;
		if (b[0] > 0) {
			s += b[0];
		}
		if (b[0] < 0) {
			s += 256 + b[0];
		}
		s *= 256;
		if (b[1] > 0) {
			s += b[1];
		}
		if (b[1] < 0) {
			s += 256 + b[1];
		}
		char ch = (char) s;
		return ch;
	}

	public static String byteToHexString(byte b) {
		String hex = "";
		hex = Integer.toHexString(b & 0xFF);
		if (hex.length() == 1) {
			hex = '0' + hex;
		}
		return hex;
	}

	public static String bytesToHexString(byte[] bs) {
		StringBuffer sb = new StringBuffer();
		String hex = "";
		for (int i = 0; i < bs.length; i++) {
			hex = Integer.toHexString(bs[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex);
		}
		return sb.toString();
	}

	public static byte[] hexStringToBytes(String in) {
		byte[] arrB = in.getBytes();
		int iLen = arrB.length;
		// 两个字符表示一个字节，所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}
}
